<template>
  <div class="p-4 h-full neo-card neo-border relative">
    <h2 class="text-lg font-semibold mb-2 text-center title-neo">故障次数排名</h2>

    <div class="flex gap-1 mb-2 self-start relative z-10">
      <button
          @click="switchToThisMonth"
          :class="[
            currentPeriod === 'thisMonth' ? 'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]' : 'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10',
            'px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300'
          ]"
      >
        本月
      </button>
      <button
          @click="switchToLastMonth"
          :class="[
            currentPeriod === 'lastMonth' ? 'bg-blue-600 text-white shadow-[0_0_8px_rgba(59,130,246,0.5)]' : 'bg-white/5 text-blue-200 hover:bg-white/10 border border-white/10',
            'px-3 py-1.5 text-xs font-medium rounded-lg transition-all duration-300'
          ]"
      >
        上月
      </button>
      </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="flex justify-center items-center h-64">
      <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
    </div>

    <!-- 图表容器 -->
    <div v-else ref="chart" class="h-64 overflow-hidden mt-4"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 响应式状态
const chart = ref(null)
const currentPeriod = ref('thisMonth') // 当前显示周期
const loading = ref(true) // 加载状态
const chartData = ref([]) // 存储 API 返回的原始数据
let chartInstance = null // ECharts 实例
let refreshInterval = null

// 颜色映射（按排名）
const colorMap = {
  0: '#EF4444', // 第1名 - 红色
  1: '#F97316', // 第2名 - 橙色
  2: '#3B82F6', // 第3名 - 蓝色
  3: '#8B5CF6', // 第4名 - 紫色
  4: '#F59E0B'  // 第5名 - 黄色
}

// 切换周期方法
const switchToThisMonth = () => {
  currentPeriod.value = 'thisMonth'
  updateChart()
}
const switchToLastMonth = () => {
  currentPeriod.value = 'lastMonth'
  updateChart()
}

// 获取数据
const fetchData = async () => {
  try {
    const res = await axios.get('/api/Notice/GetAllDeviceFaultRanking')
    if (res.data.isSuccess && res.data.data) {
      chartData.value = res.data.data
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    chartData.value = { thisMonth: [], lastMonth: [] } // 设置默认空数据
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initChart = () => {
  if (!chart.value) return
  chartInstance = echarts.init(chart.value)
}

// 更新图表
const updateChart = () => {
  if (!chartData.value || !chartInstance) return

  const data = [...chartData.value[currentPeriod.value]] // 复制数组避免修改原数据
      .sort((a, b) => b.faultCount - a.faultCount) // 降序排序（b - a 是降序，a - b 是升序）
      .slice(0, 5)
  const option = generateOption(data)
  chartInstance.setOption(option)
}

// 生成 ECharts 配置
const generateOption = (data) => {
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
    },
    grid: {
      left: '15%',
      right: '4%',
      bottom: '3%',
      top: '10%',
      containLabel: true
    },
    xAxis: { show: false },
    yAxis: {
      type: 'category',
      data: data.map(item => item.equipmentName),
      axisLine: { show: false },
      axisTick: { show: false },
      axisLabel: {
        color: '#ffffff',
        fontSize: 12
      }
    },
    series: [{
      type: 'bar',
      data: data.map((item, index) => ({
        value: item.faultCount,
        itemStyle: {
          color: colorMap[index] || '#6B7280',
          borderRadius: [4, 12, 12, 4]
        }
      })),
      barWidth: 14,
      label: {
        show: true,
        position: 'right',
        color: '#ffffff',
        fontSize: 12
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 12,
          shadowColor: 'rgba(59,130,246,0.35)'
        }
      }
    }]
  }
}

// 自适应窗口大小
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期钩子
onMounted(async () => {
  await fetchData()  // 先获取数据
  initChart()        // 初始化图表
  updateChart()      // 第一次渲染图表
  // 3秒无感刷新
  refreshInterval = setInterval(async () => {
    await fetchData()
    updateChart()
  }, 3000)
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
  }
  if (refreshInterval) {
    clearInterval(refreshInterval)
    refreshInterval = null
  }
})
</script>
